<?php

namespace app\common\model;

use think\Exception;
use think\Model;
use think\Db;

/**
 * 配置模型
 */
class UserMoneyLog extends Model
{

    // 表名,不含前缀
    protected $name = 'user_money_log';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;
    // 定义时间戳字段名
    protected $createTime = false;
    // 追加属性
    protected $append = [
    ];

    public function getCreatetimeAttr($value)
    {
        return date('Y-m-d H:i:s',$value);
    }

    public function user()
    {
        return $this->belongsTo('User', 'originUserId', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function something()
    {
        return $this->belongsTo('Something', 'something_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function auctiongood(){
        return $this->belongsTo('AuctionGood', 'good_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * @param $user_id 用户id
     * @param $page 页面
     * @return 返回数组结果集
     */
    public function getMyWithdrawals($user_id,$page,$genre){
        try{
            $where['user_money_log.user_id']=array('eq',$user_id);
            $where['user_money_log.type']=array('in',array(2,4,5,6,7,8));
            $where['user_money_log.genre']=array('eq',$genre);

            if($genre==1){
                $data=$this
                    ->with(['user','something'])
                    ->where($where) //4=分享人(收益),5=一级分享(收益),6=会员裂变(收入),7=找到物收益,8=找到失主获取收益
                    ->limit(10)
                    ->order('something.createtime desc')
                    ->page($page)
                    ->select();
            }else{
                $data=$this
                    ->with(['user','auctiongood'])
                    ->where($where) //4=分享人(收益),5=一级分享(收益),6=会员裂变(收入),7=找到物收益,8=找到失主获取收益
                    ->limit(10)
                    ->order('auctiongood.createtime desc')
                    ->page($page)
                    ->select();
            }

            $data = collection($data)->toArray();

            foreach ($data as &$row) {
                if($genre==1){
                    $row['something']['content']='“'.cut_str($row['something']['content'],14,'...').'”';
                    if($row['type']==2){

                        if($row['something']['type']==2){
                            $row['title']='找到人获得收益';
                            $row['content']='找到人';
                        }elseif ($row['something']['type']==1){
                            $row['title']='找到失主获得收益';
                            $row['content']='找到失主';
                        }elseif ($row['something']['type']==3){
                            $row['title']='找到物获得收益';
                            $row['content']='找到物';
                        }
                    }elseif ($row['type']==4){
                        $row['title']='获得收益';
                        if($row['something']['type']==2){
                            $row['content']='找到人';
                        }elseif ($row['something']['type']==1){
                            $row['content']='找到失主';
                        }elseif ($row['something']['type']==3){
                            $row['content']='找到物';
                        }
                    }elseif ($row['type']==5){
                        $row['title']='获得收益';
                        if($row['something']['type']==2){

                            $row['content']='找到人';
                        }elseif ($row['something']['type']==1){
                            $row['content']='找到失主';
                        }elseif ($row['something']['type']==3){
                            $row['content']='找到物';
                        }
                    }elseif ($row['type']==6){
                        $row['title']='收益';
                        if($row['something']['type']==2){
                            $row['content']='找到人';
                        }elseif ($row['something']['type']==1){

                            $row['content']='找到失主';
                        }elseif ($row['something']['type']==3){

                            $row['content']='找到物';
                        }
                    }
                }elseif($genre==2){
                    $row['something']['content']='“'.cut_str($row['auctiongood']['name'],14,'...').'”';
                    if($row['type']==2){
                        $row['title']='竞拍成功获得收益';
                        $row['content']='竞拍';

                    }elseif ($row['type']==4){
                        $row['title']='获得收益';
                        $row['content']='竞拍';
                    }elseif ($row['type']==5){
                        $row['title']='获得收益';
                        $row['content']='竞拍';
                    }elseif ($row['type']==6){
                        $row['title']='获得收益';
                        $row['content']='竞拍';
                    }
                }

            }


        }catch (\Exception $e){
            return [];
        }
        return $data;

    }

    /**
     * 算法
     * @param $type 类型
     * @param $publisherUserId 发布用户id
     * @param $receiverUserId 找到人/物或者失物招领用户id
     * @param $money    赏金/报酬
     * @param $something_id 找人/找物/失物招领信息id
     * @return bool 返回是否成功
     */
    public function gold($type,$publisherUserId,$receiverUserId,$money,$something_id){
        try{
            //统一时间戳
            $time=time();

            $ShareModel=new Share();
            $site=\think\Config::get('site');
            //赏金分配百分比 type=(2,3)
            $share_profit=$site['share_profit'];
            if(empty($share_profit)||$share_profit<0){
                $share_profit=0;
                //赏金分享比例
                $share_profit_share=0;
            }else{
                if($share_profit>100){
                    //赏金分配比例
                    $share_profit=1;
                    //赏金分享比例
                    $share_profit_share=0;
                }else{
                    //赏金分配比例
                    $share_profit=$share_profit/100;
                    //赏金分享比例 1减去商家分配比例
                    $share_profit_share=1-$share_profit;
                }

            }
            //报酬分配百分比 type=1
            $completed_revenue=$site['completed_revenue'];
            if(empty($completed_revenue)||$completed_revenue<0){
                //报酬分配比例
                $completed_revenue=0;
                //报酬分享比例
                $completed_revenue_share=0;
            }else {
                if($completed_revenue>100){
                    //报酬分配比例
                    $completed_revenue=1;
                    //报酬分享比例
                    $completed_revenue_share=0;
                }else{
                    //报酬分配比例
                    $completed_revenue=$completed_revenue/100;
                    //报酬分享比例1减去报酬分配比例
                    $completed_revenue_share=1-$completed_revenue;

                }
            }
            /**
             * $share_ratio 分享比例;$reward_ratio分配比例
             * $give_user_id 赏金/报酬用户id
             */
            $share_ratio=0;     //初始化
            $reward_ratio=0;    //初始化
            $give_user_id=0;    //初始化
            $originUserId=0;    //初始化


            if($type==2||$type==3){
                $share_ratio=$share_profit_share;
                $reward_ratio=$share_profit;
                $give_user_id=$receiverUserId;
                $originUserId=$publisherUserId;
                if($type==2){
                    $note='找到人获得收益';
                }else{
                    $note='找到物获得收益';
                }

            }elseif($type==1){
                $share_ratio=$completed_revenue_share;
                $reward_ratio=$completed_revenue;
                $give_user_id=$publisherUserId;
                $originUserId=$receiverUserId;
                $note='失物招领获得收益';
            }

            Db::startTrans();



            /**
             * 赏金/报酬插入数据准备
             */
            if($reward_ratio>0){
                $user = User::get($give_user_id);
                $RewardMoney=round($reward_ratio*$money,6);
                $RewardData['user_id']=$give_user_id;
                $RewardData['originUserId']=$originUserId;
                $RewardData['money']=$RewardMoney;
                $RewardData['type']=2;
                $RewardData['before']=round((float)$user->money,6);
                $RewardData['after']=round(((float)$user->money+$RewardMoney),6);
                $RewardData['note']=$note;
                $RewardData['something_id']=$something_id;
                $RewardData['createtime']=$time;

                $RewardId=Db::name('user_money_log')->insertGetId($RewardData);

                Db::name('user')
                    ->where(['id'=>array('eq',$give_user_id)])
                    ->setInc('money',round((float)$RewardMoney,6));

                Db::name('user')
                    ->where(['id'=>array('eq',$give_user_id)])
                    ->setInc('Profit_money',round((float)$RewardMoney,6));


            }

            /**
             * 所有分享获得收益
             */
            $ShareData=$ShareModel->SharingPeople($receiverUserId,$something_id);

            if($ShareData['count']>0&&$reward_ratio>0){
                $ShareMoney=round(($share_ratio*$money)/$ShareData['count'],6);
                $ShareListData=$ShareData['data'];
                foreach ($ShareListData as $key=>$val){
                    $user = User::get($val['user_id']);
                    $user_money=round((float)$user->money,6);
                    $ShareInsertData['user_id']=$val['user_id'];
                    $ShareInsertData['originUserId']=$originUserId;
                    $ShareInsertData['money']=round($ShareMoney,6);
                    $ShareInsertData['type']=4;
                    $ShareInsertData['before']=$user_money;
                    $ShareInsertData['after']=round(((float)$user_money+(float)$ShareMoney),6);
                    $ShareInsertData['note']='分享人获得收益';
                    $ShareInsertData['something_id']=$something_id;
                    $ShareInsertData['createtime']=$time;


                    Db::name('user_money_log')->insert($ShareInsertData);
                    Db::name('user')
                        ->where(['id'=>array('eq',$val['user_id'])])
                        ->setInc('money',round((float)$ShareMoney,6));
                    Db::name('user')
                        ->where(['id'=>array('eq',$val['user_id'])])
                        ->setInc('Profit_money',round((float)$ShareMoney,6));
                }
            }



            /**
             * 一级分享
             */
            $directly_under=$site['directly_under'];
            if($directly_under>0){
                if($directly_under>100){
                    $directly_under=1;
                }else{
                    $directly_under=$directly_under/100;
                }
            }else{
                $directly_under=0;
            }


            try{

                foreach ($ShareData['data'] as $key=>$val){
                    $user = User::get($val['user_id']);

                    if($directly_under>0){

                        $NextDataShare=$ShareModel->getParentShareData($val['user_id'],$val['something_id']);



                        foreach ($NextDataShare as $key=>$val_t){
                            if(!empty($val_t)&&$val_t['is_share']==1){

                                $ParenWhere['user_id']=array('eq',$val_t['user_id']);
                                $ParenWhere['something_id']=array('eq',$something_id);
                                $somethingDatNew=Something::get($val_t['something_id']);
                                if($somethingDatNew->receiverUserId==$val_t['user_id']){
                                    $ParenWhere['type']=array('eq',2);
                                }else{
                                    $ParenWhere['type']=array('eq',4);
                                }


                                $NextMoneyLogOne=$this->where($ParenWhere)->find();

                                if(!empty($NextMoneyLogOne)){
                                    $NextMoneyLogOne=$NextMoneyLogOne->toArray();

                                    if((float)$NextMoneyLogOne['money']>0){

                                        $user = User::get($val['user_id']);

                                        $ParentShareMoney=round($directly_under*(float)$NextMoneyLogOne['money'],6);

                                        $ParentInsertData['user_id']=$val['user_id'];
                                        $ParentInsertData['originUserId']=$val_t['user_id'];
                                        $ParentInsertData['money']=$ParentShareMoney;
                                        $ParentInsertData['type']=5;
                                        $ParentInsertData['before']=round((float)$user->money,6);
                                        $ParentInsertData['after']=round((float)$user->money+$ParentShareMoney,6);
                                        $ParentInsertData['note']='一级分享获得收益';
                                        $ParentInsertData['something_id']=$something_id;
                                        $ParentInsertData['createtime']=$time;

                                        Db::name('user_money_log')->insert($ParentInsertData);

                                        Db::name('user')
                                            ->where(['id'=>array('eq',$val['user_id'])])
                                            ->setInc('money',round((float)$ParentShareMoney,6));

                                        Db::name('user')
                                            ->where(['id'=>array('eq',$val['user_id'])])
                                            ->update(['Profit_money'=>round($ParentShareMoney+(float)$user->Profit_money,6)]);

                                        $update['money']=round((float)$NextMoneyLogOne['money']-$ParentShareMoney,6);


                                        Db::name('user')
                                            ->where(['id'=>array('eq',$NextMoneyLogOne['user_id'])])
                                            ->setDec('money',round((float)$ParentShareMoney,6));

                                        Db::name('user')
                                            ->where(['id'=>array('eq',$NextMoneyLogOne['user_id'])])
                                            ->setDec('Profit_money',round((float)$ParentShareMoney,6));


                                        Db::name('user_money_log')
                                            ->where($ParenWhere)
                                            ->update($update);
                                    }
                                }

                            }
                        }
                    }

                }

            }catch (\Exception $e){
                var_dump($e->getMessage());
            }


            /**
             * 会员裂变分享
             */

            $ShareDataVip=$ShareModel->VipSharingPeople($receiverUserId,$something_id);

            $directly_under=$site['total_shared'];
            if($directly_under>0){
                if($directly_under>100){
                    $directly_under=1;
                }else{
                    $directly_under=$directly_under/100;
                }
            }else{
                $directly_under=0;
            }

            if($directly_under>0){
                foreach ($ShareDataVip as $key=>$val){
                    $user = User::get($val['user_id']);
                    if($user->is_vip==1){
                        $ShareDivisionNextData=$ShareModel->getNextShareList($val['user_id'],$val['something_id']);
                        foreach ($ShareDivisionNextData as $keyD=>$valD){
                            $DivisionWhere['user_id']=array('eq',$valD['user_id']);
                            $DivisionWhere['something_id']=array('eq',$val['something_id']);
                            $somethingDatNew=Something::get($val['something_id']);
                            if($somethingDatNew->receiverUserId==$valD['user_id']){
                                $DivisionWhere['type']=array('eq',2);
                            }else{
                                $DivisionWhere['type']=array('eq',4);
                            }
                            $NextMoneyLogOne=$this->where($DivisionWhere)->find();
                            $DivisionMoney=round((float)$NextMoneyLogOne['money']*$directly_under,6);

                            $InsertData['user_id']=$val['user_id'];
                            $InsertData['originUserId']=$valD['user_id'];
                            $InsertData['money']=$DivisionMoney;
                            $InsertData['type']=6;
                            $InsertData['before']=round((float)$user->money,6);
                            $InsertData['after']=round((float)$user->money+$DivisionMoney,6);
                            $InsertData['note']='会员分裂分享获得收益';
                            $InsertData['something_id']=$something_id;
                            $InsertData['createtime']=$time;
                            Db::name('user_money_log')->insert($InsertData);

//                            Db::name('user_money_log')
//                                ->where($DivisionWhere)
//                                ->setDec('money',$DivisionMoney);

                            Db::name('user')
                                ->where(['id'=>array('eq',$val['user_id'])])
                                ->setInc('money',round((float)$DivisionMoney,6));
                            Db::name('user')
                                ->where(['id'=>array('eq',$val['user_id'])])
                                ->update(['Profit_money'=>round($DivisionMoney+(float)$user->Profit_money,6)]);
                        }



                    }

                }

            }

            Db::commit();

        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
        return true;
    }


    /**
     * 竞拍算法
     * @param $type 类型
     * @param $publisherUserId 发布用户id
     * @param $receiverUserId 竞拍成功用户id
     * @param $money    最终金额
     * @param $good_id 竞拍信息id
     * @return bool 返回是否成功
     */
    public function bidgold($publisherUserId,$receiverUserId,$money,$good_id){

        try{
            //统一时间戳
            $time=time();

            $ShareModel=new Share();
            $site=\think\Config::get('site');
            //竞拍百分比
            $share_profit=$site['bidding'];
            if(empty($share_profit)||$share_profit<0){
                $share_profit=0;
                //竞拍分享比例
                $share_profit_share=0;
            }else{
                if($share_profit>100){
                    //竞拍分配比例
                    $share_profit=1;
                    //竞拍分享比例
                    $share_profit_share=0;
                }else{
                    //竞拍分配比例
                    $share_profit=$share_profit/100;
                    //竞拍分享比例 1减去竞拍成功比例
                    $share_profit_share=1-$share_profit;
                }

            }

            /**
             * $share_ratio 竞拍分享比例;
             * $reward_ratio 竞拍成功分配比例
             * $give_user_id  竞拍成功用户id
             */



                $share_ratio=$share_profit_share;
                $reward_ratio=$share_profit;
                $give_user_id=$receiverUserId;
                $originUserId=$publisherUserId;


            Db::startTrans();



            /**
             * 竞拍成功插入数据准备
             */
            if($reward_ratio>0){

                $user = User::get($give_user_id);
                $RewardMoney=round($reward_ratio*$money,6);
                $RewardData['user_id']=$give_user_id;
                $RewardData['originUserId']=$originUserId;
                $RewardData['money']=$RewardMoney;
                $RewardData['type']=2;
                $RewardData['genre']=2;
                $RewardData['before']=round((float)$user->money,6);
                $RewardData['after']=round(((float)$user->money+$RewardMoney),6);
                $RewardData['note']='竞拍成功获得收益';
                $RewardData['something_id']=$good_id;
                $RewardData['createtime']=$time;

                $RewardId=Db::name('user_money_log')->insertGetId($RewardData);

                Db::name('user')
                    ->where(['id'=>array('eq',$give_user_id)])
                    ->setInc('money',round((float)$RewardMoney,6));

                Db::name('user')
                    ->where(['id'=>array('eq',$give_user_id)])
                    ->setInc('Profit_money',round((float)$RewardMoney,6));


            }

            /**
             * 竞拍所有分享获得收益
             */

            $ShareData=$ShareModel->BidSharingPeople($receiverUserId,$good_id);

            if($ShareData['count']>0&&$reward_ratio>0){

                $ShareMoney=round(($share_ratio*$money)/$ShareData['count'],6);
                $ShareListData=$ShareData['data'];
                foreach ($ShareListData as $key=>$val){
                    $user = User::get($val['user_id']);
                    $user_money=round((float)$user->money,6);
                    $ShareInsertData['user_id']=$val['user_id'];
                    $ShareInsertData['originUserId']=$originUserId;
                    $ShareInsertData['money']=round($ShareMoney,6);
                    $ShareInsertData['type']=4;
                    $ShareInsertData['genre']=2;
                    $ShareInsertData['before']=$user_money;
                    $ShareInsertData['after']=round(((float)$user_money+(float)$ShareMoney),6);
                    $ShareInsertData['note']='获得收益';
                    $ShareInsertData['something_id']=$good_id;
                    $ShareInsertData['createtime']=$time;


                    Db::name('user_money_log')->insert($ShareInsertData);
                    Db::name('user')
                        ->where(['id'=>array('eq',$val['user_id'])])
                        ->setInc('money',round((float)$ShareMoney,6));
                    Db::name('user')
                        ->where(['id'=>array('eq',$val['user_id'])])
                        ->setInc('Profit_money',round((float)$ShareMoney,6));
                }
            }



            /**
             * 一级分享
             */
            $directly_under=$site['bid_under'];
            if($directly_under>0){
                if($directly_under>100){
                    $directly_under=1;
                }else{
                    $directly_under=$directly_under/100;
                }
            }else{
                $directly_under=0;
            }


            try{

                foreach ($ShareData['data'] as $key=>$val){
                    $user = User::get($val['user_id']);

                    if($directly_under>0){

                        $NextDataShare=$ShareModel->BidgetParentShareData($val['user_id'],$val['something_id']);


                        foreach ($NextDataShare as $key=>$val_t){
                            if(!empty($val_t)&&$val_t['is_share']==1){

                                $ParenWhere['user_id']=array('eq',$val_t['user_id']);
                                $ParenWhere['something_id']=array('eq',$good_id);
                                $somethingDatNew=\app\common\model\AuctionGood::get($val_t['something_id']);
                                if($somethingDatNew->receiverUserId==$val_t['user_id']){
                                    $ParenWhere['type']=array('eq',2);
                                }else{
                                    $ParenWhere['type']=array('eq',4);
                                }


                                $NextMoneyLogOne=$this->where($ParenWhere)->find();

                                if(!empty($NextMoneyLogOne)){
                                    $NextMoneyLogOne=$NextMoneyLogOne->toArray();

                                    if((float)$NextMoneyLogOne['money']>0){

                                        $user = User::get($val['user_id']);

                                        $ParentShareMoney=round($directly_under*(float)$NextMoneyLogOne['money'],6);

                                        $ParentInsertData['user_id']=$val['user_id'];
                                        $ParentInsertData['originUserId']=$val_t['user_id'];
                                        $ParentInsertData['money']=$ParentShareMoney;
                                        $ParentInsertData['type']=5;
                                        $ParentInsertData['genre']=2;
                                        $ParentInsertData['before']=round((float)$user->money,6);
                                        $ParentInsertData['after']=round((float)$user->money+$ParentShareMoney,6);
                                        $ParentInsertData['note']='一级分享获得收益';
                                        $ParentInsertData['something_id']=$good_id;
                                        $ParentInsertData['createtime']=$time;

                                        Db::name('user_money_log')->insert($ParentInsertData);

                                        Db::name('user')
                                            ->where(['id'=>array('eq',$val['user_id'])])
                                            ->setInc('money',round((float)$ParentShareMoney,6));

                                        Db::name('user')
                                            ->where(['id'=>array('eq',$val['user_id'])])
                                            ->update(['Profit_money'=>round($ParentShareMoney+(float)$user->Profit_money,6)]);

                                        $update['money']=round((float)$NextMoneyLogOne['money']-$ParentShareMoney,6);


                                        Db::name('user')
                                            ->where(['id'=>array('eq',$NextMoneyLogOne['user_id'])])
                                            ->setDec('money',round((float)$ParentShareMoney,6));

                                        Db::name('user')
                                            ->where(['id'=>array('eq',$NextMoneyLogOne['user_id'])])
                                            ->setDec('Profit_money',round((float)$ParentShareMoney,6));


                                        Db::name('user_money_log')
                                            ->where($ParenWhere)
                                            ->update($update);
                                    }
                                }

                            }
                        }
                    }

                }

            }catch (\Exception $e){
                var_dump($e->getMessage());
            }


            /**
             * 竞价会员裂变分享
             */

            $ShareDataVip=$ShareModel->BidVipSharingPeople($receiverUserId,$good_id);

            $directly_under=$site['bid_total'];
            if($directly_under>0){
                if($directly_under>100){
                    $directly_under=1;
                }else{
                    $directly_under=$directly_under/100;
                }
            }else{
                $directly_under=0;
            }

            if($directly_under>0){
                foreach ($ShareDataVip as $key=>$val){
                    $user = User::get($val['user_id']);
                    if($user->is_vip==1){
                        $ShareDivisionNextData=$ShareModel->BidgetNextShareList($val['user_id'],$val['something_id']);
                        foreach ($ShareDivisionNextData as $keyD=>$valD){
                            $DivisionWhere['user_id']=array('eq',$valD['user_id']);
                            $DivisionWhere['something_id']=array('eq',$val['something_id']);
                            $somethingDatNew=\app\common\model\AuctionGood::get($val['something_id']);

                            if($somethingDatNew->receiverUserId==$valD['user_id']){
                                $DivisionWhere['type']=array('eq',2);
                            }else{
                                $DivisionWhere['type']=array('eq',4);
                            }
                            $NextMoneyLogOne=$this->where($DivisionWhere)->find();
                            $DivisionMoney=round((float)$NextMoneyLogOne['money']*$directly_under,6);

                            $InsertData['user_id']=$val['user_id'];
                            $InsertData['originUserId']=$valD['user_id'];
                            $InsertData['money']=$DivisionMoney;
                            $InsertData['type']=6;
                            $InsertData['genre']=2;
                            $InsertData['before']=round((float)$user->money,6);
                            $InsertData['after']=round((float)$user->money+$DivisionMoney,6);
                            $InsertData['note']='会员分裂分享获得收益';
                            $InsertData['something_id']=$good_id;
                            $InsertData['createtime']=$time;
                            Db::name('user_money_log')->insert($InsertData);

                            Db::name('user')
                                ->where(['id'=>array('eq',$val['user_id'])])
                                ->setInc('money',round((float)$DivisionMoney,6));
                            Db::name('user')
                                ->where(['id'=>array('eq',$val['user_id'])])
                                ->update(['Profit_money'=>round($DivisionMoney+(float)$user->Profit_money,6)]);
                        }



                    }

                }

            }

            Db::commit();

        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
        return true;
    }





}
